package cn.stylefeng.guns.modular.business.service.impl;

import static cn.stylefeng.roses.kernel.file.api.constants.FileConstants.DEFAULT_BUCKET_NAME;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.modular.business.entity.Rule;
import cn.stylefeng.guns.modular.business.mapper.RuleMapper;
import cn.stylefeng.guns.modular.business.service.RuleService;
import cn.stylefeng.guns.modular.business.utils.ScctcConst;
import cn.stylefeng.guns.modular.business.utils.WriteFileUtils;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.file.api.FileOperatorApi;
import cn.stylefeng.roses.kernel.file.api.exception.FileException;
import cn.stylefeng.roses.kernel.file.api.exception.enums.FileExceptionEnum;
import cn.stylefeng.roses.kernel.file.api.pojo.response.SysFileInfoResponse;
import cn.stylefeng.roses.kernel.file.api.util.DownloadUtil;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class RuleServiceImpl extends ServiceImpl<RuleMapper, Rule> implements RuleService {


	@Resource
    private FileOperatorApi fileOperatorApi;
	
	@Override
	public PageResult<Rule> ruleListPage(Rule rule) {
		
//		String path =  new File(ScctcConst.FILE_PATH+File.separator+DEFAULT_BUCKET_NAME , File.separator+"nihao.rules").getAbsolutePath();
//        String s = WriteFileUtils.readJsonFile(path);
//        String[] split = s.split("}\n\n");
//		System.out.println(split.length);
//		Rule addrule = null;
//        for (int i = 0; i < split.length; i++) {
//			String info = split[i];
//			String[] infoLines = info.split("\n",2);
//			addrule = new Rule();
//			addrule.setRuleCode(infoLines[0].split(" ")[1]);
//			String[] metasplit = infoLines[1].split("strings:");
//			String[] split2 = metasplit[0].split("meta:");
//			addrule.setRuleMeta(split2[split2.length-1]);
//			String[] stringsAndcondition = metasplit[1].split("condition:");
//			addrule.setRuleStrings(stringsAndcondition[0]);
//			addrule.setRuleCondition(stringsAndcondition[1]);
//			this.save(addrule);
//		}
		
		 Page<Rule> page = PageFactory.defaultPage();
        List<Rule> list = this.baseMapper.RuleList(page,rule);
        return PageResultFactory.createPageResult(page.setRecords(list));
	}

	
	public SysFileInfoResponse getFileInfoResult(String name) {

        // 获取文件字节码
        byte[] fileBytes;
        try {
            fileBytes = fileOperatorApi.getFileBytes(DEFAULT_BUCKET_NAME,name);
        } catch (Exception e) {
            log.error("获取文件流异常，具体信息为：{}", e.getMessage());
            throw new FileException(FileExceptionEnum.FILE_STREAM_ERROR);
        }

        // 设置文件字节码
        SysFileInfoResponse sysFileInfoResult = new SysFileInfoResponse();
//        BeanUtil.copyProperties(sysFileInfo, sysFileInfoResult);
        sysFileInfoResult.setFileBytes(fileBytes);

        return sysFileInfoResult;
    }


	@Override
	public void downloadRules(HttpServletResponse response,String fileName) {
		  // 根据文件名获取文件信息结果集
        SysFileInfoResponse sysFileInfoResponse = this.getFileInfoResult( fileName);
        DownloadUtil.download(fileName, sysFileInfoResponse.getFileBytes(), response);
		
	}
	
	@Override
	public void exportRules(HttpServletResponse response) {
		List<Rule> selectList = baseMapper.selectList(null);
		try {
			WriteFileUtils.writeToResource(selectList);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("导出规则写文件异常，具体信息为：{}", e.getMessage());
            throw new FileException(FileExceptionEnum.DOWNLOAD_FILE_ERROR);
		}
        SysFileInfoResponse sysFileInfoResponse = this.getFileInfoResult(ScctcConst.EXPORTR_RULE_NAME);
        DownloadUtil.download(ScctcConst.EXPORTR_RULE_NAME, sysFileInfoResponse.getFileBytes(), response);
		
	}

}
